package cn.xiaou.draw;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JOptionPane;

public class MyJButtom extends JButton{  
	private static final long serialVersionUID = 1L;
		ImageIcon img;  
        public MyJButtom(String icon){
            super();  
            this.img = new ImageIcon(icon);  
            setBorderPainted(false);  
            setContentAreaFilled(false);  
            setOpaque(false);  
            setSize(img.getIconWidth(),img.getIconHeight());  
            try{  
                bi = ImageIO.read(new File(icon));  
            }catch(Exception e){  
                JOptionPane.showMessageDialog(this,"可能是图片文件不存在","数据缺失",JOptionPane.ERROR_MESSAGE);  
                System.exit(0); 
            }  
        }  
        @Override  
        public void paintComponent(Graphics g){  
            if(this.getModel().isPressed()){  
                g.drawImage(img.getImage(),1,1,this);  
            }else{  
                g.drawImage(img.getImage(),0,0,this);  
            }  
            super.paintComponent(g);  
        }  
        BufferedImage bi ;  
        int rgb,alpha;  
        /** 
         *  设置按钮点击范围仅在图片的非透明区域。 
         */  
        @Override  
        public boolean contains(int x,int y){  
            try{  
                rgb = bi.getRGB(x,y);  
                alpha = (rgb>>24)&0xFF;  
                if(alpha==0){  
                    return false;  
                }else{  
                    return true;  
                }  
            }catch(ArrayIndexOutOfBoundsException e){  
                //当搜索到透明区域时，就getRGB抛出下表越界异常  
                return false;  
            }  
        }  
    }  
